package com.problem.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * 解题思路: 与题目66类似 但是题目66的解答只适用于增加的数字<=10的情况，其实还不是很通用，需要修改下
 * ps:因为返回结果是list 所以可以有更短的代码实现该功能，不用完全照搬题目66的解答
 *
 * @author didi
 * @DESCRIPTION
 * @create 2019-04-24 14:07
 **/

public class Problem989 {
    public List<Integer> addToArrayForm(int[] A, int K) {
        List<Integer> list   = new ArrayList<>(A.length);
        int[]         result = plusOne(A, K);
        for (int i = 0; i < result.length; i++) {
            list.add(result[i]);
        }
        return list;
    }

    private int[] plusOne(int[] digits, int num) {
        int remain = 0;
        int begin  = digits.length - 1;

        while (begin >= 0) {
            int tmp = (begin == digits.length - 1) ? (digits[begin] + num) : digits[begin];
            tmp = tmp+remain;
            remain = tmp / 10;
            tmp = tmp % 10;
            digits[begin--] = tmp;
        }
        if (remain > 0) {
            int   digit  = getNumLenght(remain);
            int[] result = new int[digits.length + digit];
            System.arraycopy(digits, 0, result, result.length - digits.length, digits.length);

            for (int i = result.length - digits.length - 1; i >= 0; i--) {
                result[i] = remain % 10;
                remain /= 10;
            }

            return result;
        } else {
            return digits;
        }
    }

    private static int getNumLenght(long num) {
        num = num > 0 ? num : -num;
        if (num == 0) {
            return 1;
        }
        return (int) Math.log10(num) + 1;
    }
}
